<template>
  <div>
    <el-form
      class="demo-form-inline"
      :model="form"
      label-width="110px"
      :rules="rules"
      ref="form"
    >
      <div class="container">
        <div class="add_container">
          <el-form-item label="活动名称：" prop="name">
            <el-input
              class="wid240"
              v-model.trim="form.name"
              placeholder="活动名称"
              @change="isEdit = true"
            ></el-input>
          </el-form-item>
          <el-form-item label="活动时间：" prop="time">
            <el-date-picker
              v-model.trim="form.time"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
              :picker-options="pickerOptions"
              @change="isEdit = true"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="满赠规则：">
            <div slot="label">
              满赠规则
              <el-tooltip
                class="item"
                effect="dark"
                placement="bottom"
              >
                <div slot="content">注释：赠送商品种类需大于0，小于等于3种</div>
                <i class="el-icon-question"></i> </el-tooltip
              >：
            </div>
            <div class="rule" v-for="(item, index) in rule_list" :key="index">
              消费满
              <el-input-number
                v-model="item.price"
                :min="item.min_price"
                :controls="false"
              ></el-input-number>
              元，送
              <div class="tabg_box">
                <el-tag
                  type="info"
                  v-for="tag in item.goods"
                  :key="tag.goods_id"
                  closable
                  @close="handleClose(tag, index)"
                  class="tagclass"
                >
                  {{ tag.goods_name }}<em>{{ tag.num }}</em
                  >{{ tag.spu_name }}
                </el-tag>
              </div>
              <span class="rule_delete"
                ><i
                  v-if="index != 3"
                  class="el-icon-plus"
                  @click="addGoods(index)"
                ></i
              ></span>
              <span class="rule_delete" v-if="index != 0"
                ><i class="el-icon-close" @click="reduceRules(index)"></i
              ></span>
            </div>
            <div class="rule">
              <el-button
                type="primary"
                @click="addRules"
                :class="{ addrule_btn: rule_list.length >= 3 }"
              >
                <i class="el-icon-plus"></i>
                添加满赠规则(最多3条)
              </el-button>
            </div>
          </el-form-item>
          <el-form-item label="商品限制：" prop="goods_limit">
            <el-radio-group v-model="form.goods_limit" @change="isEdit = true">
              <el-radio :label="0">不限制</el-radio>
              <el-radio :label="1">部分商品</el-radio>
              <el-radio :label="2">排除商品</el-radio>
            </el-radio-group>
          </el-form-item>
        </div>
        <div class="goods_container" v-show="goods_table_show">
          <div class="goods_container_header">
            <el-form-item label="商品名称：">
              <el-button
                size="mini"
                type="primary"
                icon="el-icon-plus"
                @click="openShopList"
                >选择商品</el-button
              >
            </el-form-item>
          </div>
          <div class="goods_container_body main_table">
            <el-table
              ref="multipleTable"
              :data="list"
              element-loading-text="加载中"
              fit
              border
              highlight-current-row
            >
              <el-table-column label="序号">
                <template slot-scope="scope">{{ scope.$index + 1 }}</template>
              </el-table-column>
              <el-table-column label="商品名称" :show-overflow-tooltip="true"
                ><template slot-scope="scope">
                  <div>
                    {{ scope.row.name }}【{{ scope.row.spu_name.title }}】
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                label="单位"
                prop="unit"
                :show-overflow-tooltip="true"
              />
              <el-table-column
                label="市场价"
                prop="market_price"
                :show-overflow-tooltip="true"
              />
              <el-table-column
                label="管理操作"
                prop="name"
                width="220"
                align="center"
                fixed="right"
                :show-overflow-tooltip="true"
              >
                <template slot-scope="scope">
                  <el-link @click="handeleDel(scope.row, scope.$index)"
                    >删除</el-link
                  >
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
        <div
          :class="['save_container', { positive: searchBarFixed }]"
          id="newConBox"
        >
          <el-button
            type="primary"
            @click="preservation"
            v-repeatClick
            :loading="saveloading"
            >保存</el-button
          >
          <el-button @click="$router.back(-1)">取消</el-button>
        </div>
      </div>
    </el-form>
    <!-- 选择商品弹窗 -->
    <el-dialog
      title="请选择商品"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :visible.sync="shield"
      class="main_dialog dialog900"
    >
      <div class="main_table" style="min-height: 300px">
        <el-table
          ref="multipleTable1"
          :data="dialog_goods_list"
          v-loading="loading"
          element-loading-text="加载中"
          fit
          border
          max-height="500"
          highlight-current-row
        >
          <el-table-column label="序号">
            <template slot-scope="scope">{{ scope.$index + 1 }}</template>
          </el-table-column>
          <el-table-column
            label="商品名称"
            prop="goods_name"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="单位"
            prop="spu_name"
            :show-overflow-tooltip="true"
          />
          <el-table-column label="数量">
            <template slot-scope="scope">
              <el-input-number
                class="table_input_number"
                v-model="scope.row.num"
                :min="0"
                :controls="false"
              ></el-input-number>
            </template>
          </el-table-column>
          <el-table-column
            label="市场价"
            prop="price"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="操作"
            prop="byname"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scope">
              <el-link @click="handleAddGoods(scope.row)"
                >添加</el-link
              ></template
            ></el-table-column
          >
        </el-table>
      </div>
      <div class="main_page boxdq">
        <!-- 分页 -->
        <div class="main_page_r">
          <el-pagination
            :current-page="current_sh.page"
            :page-sizes="[10, 30, 50, 100]"
            :page-size="limit_sh"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalCount_sh"
            background
            @size-change="changeLimit"
            @current-change="changePage"
          />
        </div>
        <div></div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="shield = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="选择商品" :visible.sync="shopListDialog" width="80%">
      <el-form
        ref="shopCondition"
        :inline="true"
        :model="formInline"
        class="demo-form-inline"
      >
        <el-form-item>
          <el-cascader
            :options="shopOptions"
            collapse-tags
            :props="props"
            clearable
            @change="changeCasader"
            style="width: 230px"
          ></el-cascader>
        </el-form-item>
        <el-form-item>
          <el-input
            placeholder="商品名称/编号/助记码"
            v-model="formInline.name"
            clearable
          >
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="info" @click="reset">重置</el-button>
          <el-button type="primary" @click="onSubmit">查询</el-button>
        </el-form-item>
      </el-form>
      <market-dialog
        ref="market"
        :loadingDialig="loadingDialig"
        :totle="totle"
        :tableList="tableData"
        @changeList="changeList"
        @changeCurrent="changeCurrent"
        @deleteList="deleteList"
      ></market-dialog>
      <span slot="footer" class="dialog-footer">
        <el-button @click="shopListDialog = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import rules from "@/rules/marketing/marketing_full.js";
import {
  get_full_add,
  get_full_getGoodsSpu,
  get_full_getGoodsSpus,
  get_full_getUndercarriage,
} from "@/api/marketing/marketing.js";
import { apiUrl, objKeySort, Md5 } from "@/utils/public";

import MarketDialog from "@/components/MarketDialog/index";
// 获取分类树列表
import { category_index } from "@/api/commodity/commodityClassification";
export default {
  components: {
    MarketDialog,
  },
  data() {
    return {
      rules,
      list: [],
      // 弹窗商品
      dialog_goods_list: [],
      // 监听滚动
      searchBarFixed: false,
      form: {
        name: "",
        start_time: "",
        end_time: "",
        time: [],
        type: 2, //满减满赠类型  type1  满减  2 满赠
      },
      // 活动时间
      time: [],
      //规则
      rule_list: [
        {
          price: 0,
          min_price: 0,
          goods: [],
        },
      ],
      goods_table_show: false,

      // 弹窗商品名称搜索
      loading: false,
      form_sh: {
        name: "",
      },
      current_sh: {
        page: 1,
        per_page: 10,
      },
      limit_sh: 10,
      totalCount_sh: 1,
      shield: false,
      pickerOptions: {
        disabledDate(time) {
          let now = new Date();
          now.setHours(0);
          now.setMinutes(0);
          now.setSeconds(0);
          now.setMilliseconds(0);
          return time.getTime() < now.getTime();
        },
      },
      // 满赠规则索引
      rules_index: "",
      goods_name: "",
      saveloading: false,
      isEdit: false,

      // 商品模态框的表格
      tableData: [],
      loadingDialig: false,
      totle: 0,
      // 控制选择商品模态框
      shopListDialog: false,
      formInline: {
        name: null,
        category_ids: null,
        status: 1,
      },
      // 商品分类树
      shopOptions: [],
      // 商品分类树的格式
      props: {
        multiple: true,
        value: "id",
        label: "title",
        children: "selfNext",
      },
    };
  },
  watch: {
    "form.goods_limit": {
      handler(val) {
        if (!val) {
          this.goods_table_show = false;
        } else {
          val != 0
            ? (this.goods_table_show = true)
            : (this.goods_table_show = false);
        }
      },
      deep: true,
      immediate: true,
    },
  },
  methods: {
    // 监听滚动
    handleScroll() {
      return;
    },
    // 添加规则
    addRules() {
      this.isEdit = true;
      let length = this.rule_list.length;
      if (this.rule_list.length < 3) {
        this.rule_list.push({
          price: this.rule_list[length - 1].price + 0.01,
          min_price: this.rule_list[length - 1].price + 0.01,
          goods: [],
        });
      } else {
        return;
      }
    },
    // 减少规则
    reduceRules(index) {
      this.rule_list.splice(index, 1);
    },
    // 删除商品
    handleClose(tag, index) {
      let goods = this.rule_list[index].goods;
      goods.splice(goods.indexOf(tag), 1);
    },
    //添加商品弹窗事件
    addGoods(index) {
      this.rules_index = index;
      this.shield = true;
    },
    // 弹窗添加商品
    handleAddGoods(data) {
      if (this.rule_list[this.rules_index].goods.includes(data)) {
        let index = this.rule_list[this.rules_index].goods.indexOf(data);
        this.rule_list[this.rules_index].goods[index].num = data.num;
        this.shield = false;
        return;
      }
      if (!data.num) {
        this.$message.warning("赠送商品数量不能为0");
        return;
      }
      if (this.rule_list[this.rules_index].goods.length < 3) {
        this.rule_list[this.rules_index].goods.push(data);
      } else {
        data.num = 0;
        this.$message.warning("赠送商品数量最多只可以添加3个");
      }
      this.shield = false;
    },
    // 分页
    changeLimit(pageSize) {
      this.current_sh.per_page = pageSize;
      this.getDiaGoods();
    },
    changePage(page) {
      this.current_sh.page = page;
      this.getDiaGoods();
    },
    // 获取商品
    querySearchAsync(queryString, cb) {
      let name = queryString || "";
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        {
          name: name,
          status: 1,
        }
      );
      get_full_getGoodsSpu(data).then((res) => {
        if (res.errcode == 0) {
          if (this.$refs.searchSelect) {
            this.$refs.searchSelect.activated = true;
          }
          var results = res.data.list;
          cb(results);
        } else {
          this.$message.error(res.errmsg);
          cb([]);
        }
      });
    },
    // 商品选择
    handleSelect(item) {
      this.isEdit = true;
      let obj = {
        goods_id: item.goods_id,
        goods_spu_id: item.id,
        goods_name: item.goods.name,
        spu_name: item.spu_name.title,
        unit: item.spu_unit.title,
        price: item.market_price,
      };
      let flag = false;
      this.list.map((e) => {
        if (e.goods_spu_id == item.id) {
          flag = true;
        }
      });
      flag ? "" : this.list.push(obj);
    },
    handeleDel(index) {
      let market = this.$refs.market;
      let newIndex = market.rowActiveList.findIndex(
        (item) => item.id == row.id
      );
      market.rowActiveList.splice(newIndex, 1);
      this.list.splice(index, 1);
    },
    // 弹窗选择获取商品
    getDiaGoods() {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        {
          status: 0,
        },
        this.current_sh
      );
      this.loading = true;
      get_full_getUndercarriage(data)
        .then((res) => {
          let arr = [];
          if (res.errcode == 0) {
            res.data.list.data.map((item) => {
              let obj = {
                goods_id: item.goods_id,
                goods_spu_id: item.id,
                goods_name: item.goods.name,
                spu_name: item.spu_name.title,
                num: "",
                price: item.market_price,
              };
              arr.push(obj);
            });
            this.totalCount_sh = res.data.list.total;
            this.dialog_goods_list = arr;
            this.loading = false;
          }
        })
        .catch((error) => {});
    },

    // 保存
    preservation() {
      // 后端接口报错
      this.$refs.form.validate((valid) => {
        if (valid) {
          let form = this.list_form();
          if (!form) {
            return;
          }
          let goods_data = JSON.parse(form.goods_data);
          let goods_limit = form.goods_limit;
          if (goods_limit != 0 && goods_data.length == 0) {
            this.$message.error("请添加商品");
            return;
          }
          this.saveloading = true;
          let data = Object.assign(
            {
              sign: Md5(
                objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
              ),
            },
            apiUrl().name,
            form
          );
          get_full_add(data).then((res) => {
            if (res.errcode == 0) {
              this.$message.success("添加成功");
              this.saveloading = false;
              this.form = {
                name: "",
                start_time: "",
                end_time: "",
                goods_limit: null,
                time: [],
                type: 2,
              };
              this.list = [];
              this.dialog_goods_list = [];
              this.getDiaGoods();
              this.rule_list = [];
              this.isEdit = false;
              this.$emit("back");
            } else {
              this.$message.warning(res.errmsg);
              this.saveloading = false;
            }
          });
        }
      });
    },
    list_form() {
      let form = JSON.parse(JSON.stringify(this.form));
      form.start_time = form.time ? form.time[0] : "";
      form.end_time = form.time ? form.time[1] : "";
      delete form.time;
      // goods_data
      let list = this.list.map((item) => {
        return {
          goods_id: item.goods_id,
          goods_spu_id: item.id,
          goods_name: item.name,
          spu_name: item.spu_name.title,
          unit: item.spu_unit.title,
          price: item.market_price,
        };
      });
      form.goods_data = JSON.stringify(list);
      // rule
      let rule = JSON.parse(JSON.stringify(this.rule_list));

      let flag = false;
      for (let index = 0; index < rule.length; index++) {
        const e = rule[index];
        delete e.min_price;
        e.goods.map((p) => {
          delete p.price;
        });
        if (e.price == 0) {
          this.$message.error("消费价格不能为0");
          flag = true;
          break;
        }
        if (e.goods.length == 0) {
          this.$message.error("赠送商品不能为空");
          flag = true;
          break;
        }
      }
      form.rule = JSON.stringify(rule);
      return flag ? false : form;
    },

    // 获取商品列表
    getGoodsIndex() {
      return new Promise((resolve, reject) => {
        this.$nextTick(() => {
          let data = {
            name: this.formInline.name,
            category_ids: this.formInline.category_ids,
            status: this.formInline.status,
            page: this.$refs.market.pagi.page,
            size: this.$refs.market.pagi.pageSize,
          };
          let query = this.packageApi(data);
          get_full_getGoodsSpus(query).then((res) => {
            if (res.errcode == 0) {
              resolve(res.data);
            } else {
              reject(res.errmsg);
            }
          });
        });
      });
    },
    // 获取分类树列表
    getCation() {
      return new Promise((resolve, reject) => {
        let data = {
          filter: true,
        };
        let query = this.packageApi(data);
        category_index(query).then((res) => {
          if (res.errcode == 0) {
            resolve(res.data.category);
          } else {
            reject(res.errmsg);
          }
        });
      });
    },

    // 打开选择商品模态框
    async openShopList() {
      /**
       * 1、制空上次通过多选框激活的数据列表
       * 2、打开商品模态框与加载功能
       * 3、调用商品列表接口获取商品列表数据
       * 4、判断list的数据列表中是否存在数据内容，存在，则将商品列表中的状态修改为true，反之赋值为false
       * 5、关闭加载功能
       */
      this.loadingDialig = true;
      this.shopListDialog = true;
      let list = await this.getGoodsIndex();
      // let list = [
      //   {
      //     id: "1",
      //     date: "2016-05-03",
      //     name: "王小虎",
      //     address: "上海市普陀区金沙江路 1518 弄",
      //   },
      //   {
      //     id: "2",
      //     date: "2016-05-02",
      //     name: "王小虎",
      //     address: "上海市普陀区金沙江路 1518 弄",
      //   },
      //   {
      //     id: "3",
      //     date: "2016-05-04",
      //     name: "王小虎",
      //     address: "上海市普陀区金沙江路 1518 弄",
      //   },
      //   {
      //     id: "4",
      //     date: "2016-05-01",
      //     name: "王小虎",
      //     address: "上海市普陀区金沙江路 1518 弄",
      //   },
      //   {
      //     id: "5",
      //     date: "2016-05-08",
      //     name: "王小虎",
      //     address: "上海市普陀区金沙江路 1518 弄",
      //   },
      //   {
      //     id: "6",
      //     date: "2016-05-06",
      //     name: "王小虎",
      //     address: "上海市普陀区金沙江路 1518 弄",
      //   },
      //   {
      //     id: "7",
      //     date: "2016-05-07",
      //     name: "王小虎",
      //     address: "上海市普陀区金沙江路 1518 弄",
      //   },
      // ];
      // 将获取到的表格列表格式化后赋值给this.tableData
      this.tableData = this.echoList(list.list);
      this.totle = list.count;
      this.$nextTick(() => {
        this.loadingDialig = false;
      });
    },
    // 选中的商品回显回模态框
    echoList(list) {
      // 先将获取到的商品数据中添加两个字段，分别是check(是否选中), disabled(是否禁止选中)
      let newList = list.map((item) => {
        item.check = false;
        item.disabled = false;
        return item;
      });
      // 需要回显的数据
      let newEacoList = this._.cloneDeep(this.list);
      // 通过循环将回显中的数据在获取到的列表中状态进行修改
      for (let i = 0; i < newList.length; i++) {
        for (let j = 0; j < newEacoList.length; j++) {
          if (newList[i].id == newEacoList[j].id) {
            newList[i].check = true;
            newList[i].disabled = true;
            break;
          } else continue;
        }
      }
      return newList;
    },
    // 重置商品模态框的搜索条件
    reset() {
      this.$refs.shopCondition.resetFields();
    },
    //
    // 商品模态框的搜索
    onSubmit() {
      this.openShopList();
    },
    // 获取组件内点击添加的数据并追加至list中即可
    changeList(obj) {
      this.list.push(obj);
      let _this = this;
      function deWeightThree() {
        let map = new Map();
        for (let item of _this.list) {
          if (!map.has(item.name)) {
            map.set(item.id, item);
          }
        }
        return [...map.values()];
      }
      this.list = deWeightThree();
    },
    // 完成商品列表的勾选所触发的函数
    save() {
      /**
       * this.$refs.market.rowActiveList:获取通过左侧勾选的数据列表
       * 将两个数据列表进行合并并深克隆
       * 将最终数据赋值给this.list
       */
      // let market = this.$refs.market;
      // let list = this._.cloneDeep(market.rowActiveList);
      // this.list = list;
      this.shopListDialog = false;
    },
    // 切换页数
    changeCurrent(e) {
      this.openShopList();
    },
    // 封装请求的sign和timeStamp字段
    packageApi(data = {}) {
      let query = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        data
      );
      return query;
    },
    // 分类树修改事件
    changeCasader(e) {
      let list = e.map((item) => {
        let last = item.at(-1);
        return last;
      });
      this.formInline.category_ids = list.join(",");
    },
    // 删除list上数据
    deleteList(list) {
      let index = this.list.findIndex((item) => item.goods_id == list.goods_id);
      this.list.splice(index, 1);
    },
  },
  async created() {
    this.shopOptions = await this.getCation();
    this.getDiaGoods();
  },
};
</script>

<style lang="scss" scoped>
.container {
  padding: 0 20px;
  margin-top: 15px;
}

// 满减规则
.rule {
  display: flex;
  align-items: center;
  &:not(:first-child) {
    margin-top: 10px;
  }
  /deep/.el-input-number {
    width: 80px;
    margin: 0 8px;
  }
  .rule_delete {
    width: 20px;
    font-size: 20px;
    font-weight: 900;
    margin-left: 15px;
  }
  .addrule_btn {
    cursor: not-allowed;
    background-color: #ebebeb;
    border-color: #ebebeb;
    color: #606266;
  }
  .tabg_box {
    min-width: 220px;
    min-height: 32px;
    margin-left: 5px;
    border-radius: 4px;
    border: 1px solid #dcdfe6;
    box-sizing: border-box;
    background-color: #fff;
    display: flex;
    align-items: center;
    /deep/ .el-tag {
      margin: 0 5px;
    }
    /deep/ .el-icon-close::before {
      transform: translateY(1px) translateX(-1px);
    }
    &:hover {
      border-color: #c0c4cc;
    }
  }
}
// 商品限制
/deep/ .el-radio__inner {
  &:hover {
    border-color: #03a98e;
  }
}
.item {
  vertical-align: middle;
  font-size: 16px;
  transform: translateY(-2px);
}

// 商品盒子
.goods_container_header {
  display: flex;
  align-items: flex-start;
  .el-button {
    margin-left: 15px;
  }
}
.goods_container_body {
  padding: 0 20px;
}
.save_container {
  padding: 0 20px;
  margin-top: 15px;
  &.positive {
    position: fixed;
    bottom: 50px;
    left: 0;
    z-index: 9999;
  }
}

// 弹窗
.table_input_number {
  /deep/.el-input-number {
    width: 80px;
    margin: 0 8px;
  }
}
/deep/.main_table .el-table--small td .cell {
  height: auto;
  .el-input {
    width: 80px;
  }
}
/deep/ .mainor_form form {
  width: auto;
}
.main_page {
  display: flex;
  justify-content: flex-end;
}
.tagclass {
  background-color: #f0f9eb;
  border-color: #e1f3d8;
  color: #67c23a;
  em {
    padding: 0 3px;
  }
}
.main_name {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  padding: 5px 0;
  height: 50px;

  .main_addr {
    color: #999;
  }

  span {
    line-height: 20px;
    display: inline;
    height: 20px;
  }
}
</style>